<?php
declare (strict_types=1);

namespace app\service;

use think\App;
use think\facade\Db;
use app\model\FetchTaskModel;
use app\model\FetchUrlModel;
use app\model\FetchLogModel;

class MarketSaveService extends \think\Service
{

    static $dao;

    function __construct(App $app)
    {
        self::$dao = Db::table('eb_market');
    }

    static function saveJson()
    {
        $dir = app_path('data/json');
        $fileSet = glob($dir . '/*.json');
        foreach ($fileSet as $file) {

            $json = file_get_contents($file);
            $data = json_decode($json, true);

            $data['synopsis'] = $data['snopi'];
            $data['content'] = $data['desc'];
            unset($data['snopi']);
            if (!isset($data['items'])) {
                continue;
            }
            foreach ($data['items'] as $key => $item) {
                if (is_int(strpos($key, '面积'))) {
                    $data['building_area'] = $item;
                }
                if (is_int(strpos($key, '时间')) or is_int(strpos($key, '日期'))) {
                    if (preg_match('/\d{4}/', $item)) {
                        $data['open_date'] = self::formatDate($item);
                    }

                }
                if (is_int(strpos($key, '地址'))) {
                    $data['address'] = $item;
                }
                if (is_int(strpos($key, '人'))) {
                    $data['contact'] = $item;
                }
                if (is_int(strpos($key, '电话'))) {
                    $data['phone'] = $item;
                }
                if (is_int(strpos($key, '企业')) or is_int(strpos($key, '所属'))) {
                    if (!is_int(strpos($item, '查看'))) {
                        $data['company'] = $item;
                    }
                }
            }
            unset($data['items'], $data['c'], $data['desc'], $data['file']);
           echo "\n", Db::table('eb_market')->insertGetId($data);
        }
    }

    static function formatDate($date)
    {
        $date = preg_replace('/[^\d]/', '-', $date);
        $date = preg_replace('/\-+/', '-', $date);
        $date = trim($date, '-');
        $count = substr_count($date, "-");
        if (0 == $count) {
            $date .= "-01-01";
        } elseif (1 == $count) {
            $date .= "-01";
        } else {
            $es = explode('-', $date);
            $date = "$es[0]-$es[1]-$es[2]";
        }
        return $date;
    }
}
